package cn.coder.mybatis.javamail.service;

import cn.coder.mybatis.javamail.model.SendEmail;
import sun.misc.BASE64Decoder;

import javax.mail.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Properties;

/**
 * Created by threegrand2 on 15-1-8.
 * java接受邮件
 */
public class SimpleReceiveMailService {
    private String disposition = null;
    private BodyPart  bodyPart = null;


    //处理任何一种邮件信息
    public void handle(Message message) throws Exception{
        System.out.println("邮件主题: "+message.getSubject());
        System.out.println("邮件作者："+message.getFrom()[0].toString());
        System.out.println("发送日期："+message.getSentDate());
    }

    //处理文本格式的文件
    public void handleText(Message message) throws Exception{
        this.handle(message);
        System.out.println("邮件内容： "+message.getContent());
    }

    //处理Mulitpart邮件，并保存附件
    public void handleMulitpart(Message message ) throws Exception{
        Multipart multipart = (Multipart)message.getContent();
        int count = multipart.getCount();
        for(int i =0;i<count;i++){
            this.handle(message);
            bodyPart = multipart.getBodyPart(i);
            disposition =bodyPart.getDisposition();
            if(disposition != null && disposition.equals(bodyPart.ATTACHMENT)){
                saveMulitFile(bodyPart);    //保存附件
            }else{
                //没有附件，就显示内容
                System.out.println(bodyPart.getContent());
            }
        }
    }

    //保存附件
    public static void saveMulitFile(BodyPart bodyPart)throws Exception{
        String tmp= bodyPart.getFileName();
        String s = tmp.substring(8,tmp.indexOf("=?"));
        //文件名使用的是base64，这里解码，获取文件名
        String filename = base64Decoder(s);
        System.out.println("附件名称： "+filename);
        InputStream  inputStream = bodyPart.getInputStream();

        FileOutputStream writer = new FileOutputStream(new File(""));   //这里填入保存附件的本地地址
        byte [] content = new byte[255];
        int read = 0;
        while( (read =inputStream.read(content)) != -1 ){
            writer.write(content);
        }
        writer.close();
        inputStream.close();
    }
    //对文件名进行解码
    public static String base64Decoder(String string) throws Exception{
        sun.misc.BASE64Decoder  base64Decoder = new BASE64Decoder();
        byte [] b = base64Decoder.decodeBuffer(string);
        return new String(b);
    }

    /**
     * 获取邮件的核心方法
     * @param sendEmail
     * @throws Exception
     */
    public static void receiveMail(SendEmail sendEmail)throws Exception{
        Properties properties = sendEmail.getMailProperties();
        Session session = Session.getDefaultInstance(properties);
        Store store = session.getStore("pop3");
        store.connect(sendEmail.getMailServerHost(),sendEmail.getUserName(),sendEmail.getUserPass());
        Folder   folderiInbox = store.getDefaultFolder().getFolder("INBOX");
        folderiInbox.open(Folder.READ_WRITE);
        Message [] message =folderiInbox.getMessages();
        FetchProfile  fetchProfile = new FetchProfile();
        fetchProfile.add(FetchProfile.Item.ENVELOPE);
        folderiInbox.fetch(message,fetchProfile);
        for(int i = 0;i < message.length;i ++){
            message[i].setFlag(Flags.Flag.DELETED, true);
        }
        if(folderiInbox != null){
            //关闭为true的时候表示阅读完邮件后，将邮件删除。可以参考，mail jar API
            folderiInbox.close(false);
        }
        if(store != null){
            store.close();
        }
    }
}
